<template>
	<!-- 招标合同协同审批单详情 -->
	<div class="tenderContractDetails">
		<CommonTitle titleName="招标合同协同审批单">
			<template #rightCnBox>
				<el-button
					style="margin-left: auto"
					v-if="pageType === 'view'"
					@click="toPath"
          class="button_edit"
					>查看审批流程</el-button
				>
			</template>
		</CommonTitle>
		<div class="contenForm">
			<el-form
				:inline="true"
				:model="state"
				class="demo-form-inline"
				:rules="rules"
				status-icon
				ref="formInlineRef"
				:disabled="pageType === 'view'"
				:hide-required-asterisk="pageType === 'view'"
			>
				<el-row class="row-bg" justify="space-between">
					<el-col :span="8" v-if="pageType === 'view'">
						<el-form-item label="审批单编号:" label-width="180">
							<el-input disabled v-model="state.businessId" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="pageType === 'view'">
						<el-form-item label="审批状态:" label-width="180">
							<el-select disabled v-model="state.auditStatus" placeholder="">
								<el-option label="" value="-" />
								<el-option
									v-for="v in auditStatusOptions"
									:key="v.value"
									:label="v.label"
									:value="v.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="pageType === 'view'"> </el-col>
					<el-col :span="8">
						<el-form-item label="关联项目:" label-width="180">
							<el-select
								disabled
								v-model="state.projectMainName"
								placeholder=""
							>
								<el-option label="" value="-" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="关联招标任务:" label-width="180">
							<el-input
								disabled
								v-model="state.projectTaskName"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="任务来源:" label-width="180">
							<el-input v-model="state.taskSource" placeholder="" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<!-- 招标方式 -->
						<el-form-item label="合同签约方式:" label-width="180">
							<el-select
								disabled
								v-model="state.tenderTypeExplain"
								placeholder=""
							>
								<el-option
									v-for="v in selectionTypeOptions"
									:key="v.value"
									:label="v.label"
									:value="v.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="合同结算方式:"
							label-width="180"
							prop="contractSettlementType"
						>
							<el-select
								:disabled="pageType === 'view'"
								v-model="state.contractSettlementType"
								placeholder=""
							>
								<el-option
									v-for="v in contractSettlementTypeOptions"
									:key="v.value"
									:label="v.label"
									:value="v.value"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="合同名称:"
							label-width="180"
							prop="contractName"
						>
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.contractName"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="合同编号:" label-width="180" prop="contractId">
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.contractId"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
          <el-col :span="8">
          <el-form-item label="合同/协议类别" prop="contractAgreementCategory" label-width="180">
            <el-select
              :disabled="pageType === 'view'"
              v-model="state.contractAgreementCategory"
              placeholder="请选择合同/协议类别"
            >
              <el-option v-for="item in typeArr" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同归属部门" prop="responsibleDepartmentId" label-width="180">
            <el-select
              :disabled="pageType === 'view'"
              v-model="state.responsibleDepartmentId"
              placeholder="请选择合同归属部门"
            >
              <el-option v-for="item in departmentArr" :label="item.departmentName" :value="item.departmentId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额描述" prop="contractAmountDescription" label-width="180">
            <el-input
              :disabled="pageType === 'view'"
              v-model="state.contractAmountDescription"
              placeholder="请输入合同金额描述"
            />
          </el-form-item>
        </el-col>
					<el-col :span="8">
						<el-form-item label="签约甲方:" label-width="180" prop="signPartyA">
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.signPartyA"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="签约乙方:" label-width="180" prop="signPartyB">
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.signPartyB"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
          <el-col :span="8">
						<el-form-item label="签约三方:" label-width="180" prop="signPartyThree">
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.signPartyThree"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="合同金额:"
							label-width="180"
							prop="contractAmount"
						>
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.contractAmount"
								@input="state.contractAmount = limitInputNum(state.contractAmount,10,2,true)"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="8">
						<el-form-item label="服务期限:" label-width="180" prop="value1">
							<el-date-picker
								v-model="state.value1"
								type="daterange"
								range-separator="-"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="YYYY-MM-DD"
								format="YYYY-MM-DD"
								:disabled="pageType === 'view'"
							/>
						</el-form-item>
					</el-col> -->
					<el-col :span="8">
						<el-form-item
							label="质保期:"
							label-width="180"
							prop="warrantyExplain"
						>
							<el-input
								:disabled="pageType === 'view'"
								v-model="state.warrantyExplain"
								placeholder=""
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item
							label="资金流向:"
							label-width="180"
							prop="capitalFlow"
						>
							<el-select
								class="global-el-input"
								v-model="state.capitalFlow"
								disabled
								placeholder="请选择"
							>
								<el-option value="1" label="收款合同" />
								<el-option value="2" label="付款合同" />
							</el-select>
						</el-form-item>
					</el-col>
          <el-col :span="8" v-if="pageType === 'view'">
          <el-form-item label="合同协议编码" prop="contractAgreementCode" label-width="180">
            <el-input
              :disabled="pageType === 'view'"
              v-model="state.contractAgreementCode"
              placeholder="请输入合同协议编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="pageType === 'view'">
          <el-form-item label="服务期限" prop="serviceTime" label-width="180">
            <el-input
              :disabled="pageType === 'view'"
              v-model="state.serviceTime"
              placeholder="请输入服务期限"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="pageType === 'view'"> </el-col>
					<el-col :span="24">
						<el-form-item
							label="合同内容:"
							label-width="180"
							prop="contractContent"
						>
							<el-input
								:disabled="pageType === 'view'"
								type="textarea"
								:rows="4"
								v-model="state.contractContent"
								placeholder="多行输入"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="支付方式:" label-width="180" prop="payExplain">
							<el-input
								:disabled="pageType === 'view'"
								type="textarea"
								:rows="4"
								v-model="state.payExplain"
								placeholder="多行输入"
							/>
						</el-form-item>
					</el-col>
					<!-- 合同结算计划 -->
					<form-tabel
						ref="formtabelRef"
						:pageType="pageType"
						:payList="state.payList"
					></form-tabel>

					<el-col :span="24">
						<el-form-item label="备注:" label-width="180">
							<el-input
								:disabled="pageType === 'view'"
								type="textarea"
								:rows="4"
								v-model="state.remark"
								placeholder="多行输入"
							/>
						</el-form-item>
					</el-col>

					<div class="submitBth">
						<el-button
							@click="saveApplyContract"
							:loading="BtnLoading"
							v-if="pageType == 'edit'"
              class="button_funtion"
							>发起审批</el-button
						>
					</div>
				</el-row>
			</el-form>
		</div>

		<!-- 相关附件 -->
		<div class="card_box m-t40">
			<attachment-details
				:pageType="pageType"
				:tenderTaskId="tenderTaskId"
				:businessId="state.businessId"
				:businessType="13"
				:file-list="state.files"
				@onSuccess="onSuccess"
			></attachment-details>
		</div>

		<div class="title_ m-t40 m-b20">其他信息</div>
		<div class="other m-r20 d-flex">
			<div class="other_item d-flex">
				<div class="lebel">申请人</div>
				<div class="conetnt m-l10">{{ state.applyUserName }}</div>
			</div>
			<div class="other_item d-flex">
				<div class="lebel">申请部门</div>
				<div class="conetnt m-l10">{{ state.applyUserDeptName }}</div>
			</div>
			<div class="other_item d-flex">
				<div class="lebel">创建时间</div>
				<div class="conetnt m-l10">{{ state.createTime }}</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";
import {
	ElForm,
	ElCol,
	ElRow,
	ElUpload,
	ElCheckbox,
	ElSelect,
	ElDatePicker,
	ElTable,
	ElMessage,
	ElMessageBox,
} from "element-plus";
import {ref, reactive, onMounted, watch, nextTick} from "vue";
import { useStore } from "vuex";
import {
	contractSettlementTypeOptions,
	selectionTypeOptions,
	auditStatusOptions,
} from "@/common/dict/dictCollect";
import { useRoute, useRouter } from "vue-router";
import { approveApi } from "@/api/biddingProject";
import FormTabel from "./components/FormTabel.vue";
import AttachmentDetails from "./components/AttachmentDetails.vue";
import { getURLhandler } from "@/views/constructionProjectManage/static/utools.js";
import { department } from '@/api/project'
import {limitInputNum} from "@/common/utils/GlobalUtils";
import {useSetFormData} from "@/hooks/setFormData";

const router = useRouter();
const route = useRoute();
const tenderTaskId = getURLhandler(route.path).tenderTaskId;
const pageType = ref(getURLhandler(route.path).pageType);
const businessId = getURLhandler(route.path).businessId;
const BtnLoading = ref(false);

let state = reactive({});

const {
	setData,
	getData,
	getAttributeNum,
	filterEmptyAttributes,
} = useSetFormData({
	key:`tenderContractDetails-${getURLhandler(route.path).tenderTaskId}-pageType${getURLhandler(route.path).pageType}`,
});

const rules = reactive({
	contractSettlementType: [
		{
			required: pageType !== "view" ? true : false,
			message: "请选择合同结算方式",
			trigger: ["change", "blur"],
		},
	],
	contractContent: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入合同内容",
			trigger: "blur",
		},
	],
	contractName: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入合同名称",
			trigger: "blur",
		},
	],
	contractId: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入合同编号",
			trigger: "change",
		},
  ],
  contractAgreementCategory: [
    {
			required: pageType !== "view" ? true : false,
			message: "请选择合同/协议类别",
			trigger: "blur",
		},
  ],
  responsibleDepartmentId: [
    {
			required: pageType !== "view" ? true : false,
			message: "请选择合同归属部门",
			trigger: "blur",
		},
  ],
  contractAmountDescription: [
    {
			required: pageType !== "view" ? true : false,
			message: "请输入合同金额描述",
			trigger: "blur",
		},
  ],
	signPartyA: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入签约甲方",
			trigger: "change",
		},
	],
	signPartyB: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入签约乙方",
			trigger: "change",
		},
  ],
/*  signPartyThree: [
    {
			required: pageType !== "view" ? true : false,
			message: "请输入签约三方",
			trigger: "change",
		},
  ],*/
	contractAmount: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入合同金额",
			trigger: "change",
		},
	],
	// value1: [
	// 	{
	// 		required: pageType !== "view" ? true : false,
	// 		message: "请选择服务期限",
	// 		trigger: "change",
	// 	},
	// ],
	warrantyExplain: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入质保期",
			trigger: "change",
		},
	],
	capitalFlow: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入资金流向",
			trigger: "change",
		},
	],
	payExplain: [
		{
			required: pageType !== "view" ? true : false,
			message: "请输入支付方式",
			trigger: "change",
		},
	],
});

const typeArr = [
  {
    label: '修缮改造类（非工程建设）',
    value: 1
  },
  {
    label: '物资采购类（非工程建设）',
    value: 2
  },
  {
    label: '物业服务类（非工程建设）',
    value: 3
  },
  {
    label: '其他服务类（非工程建设）',
    value: 4
  },
  {
    label: '设施设备系统维保及维修类（非工程建设）',
    value: 5
  },
  {
    label: '施工类（工程建设）',
    value: 6
  },
  {
    label: '与工程建设有关的重要设备、材料等货物采购类（工程建设）',
    value: 7
  },
  {
    label: '勘察、设计、监理服务类（工程建设）',
    value: 8
  },
  {
    label: '检查、检测、咨询、测绘、图审等其他工程服务类（工程建设）',
    value: 9
  },
  {
    label: '资产租售类',
    value: 10
  },
  {
    label: '办公物资类',
    value: 11
  },
];

const update = () => {};

const onSubmit = () => {};

const isBool = ref(false);
watch([()=>pageType,()=>state],(newVal)=>{
	if(newVal[0].value==='edit' &&  Object.keys(newVal[1]).length > 1 && isBool.value){
		setData(state);
	}
},{deep:true})

const getApplyContractInfo = () => {
	approveApi
		.getApplyContractInfo({
			tenderTaskId,
			businessId: businessId,
		})
		.then(async (res) => {
			if (res.code === '200') {
				let data = res.data || {};

				if (getURLhandler(route.path).pageType === 'edit') {
					if (getAttributeNum(await getData()) > getAttributeNum(data)) { // 缓存中的数据比接口数据的多
						data = Object.assign({},await getData(), filterEmptyAttributes(data))
					}
					if (getAttributeNum(await getData()) <= getAttributeNum(data)) { // 缓存中的数据比接口数据的少或者相同
						data = filterEmptyAttributes(data)
					}
				}

				for (let key in data) {
					if (data[key]) {
						state[key] = data[key];
					}
					if (!state.capitalFlow) {
						state.capitalFlow = "2";
					}
				}

				await nextTick(() => {
					isBool.value = true;
				})
			}
		});
};

const onSuccess = (arr) => {
  state.files = arr;
}

const formInlineRef = ref(null);
const formtabelRef = ref(null);
const saveApplyContract = () => {
	if(!state.files.length){
		return ElMessage.warning('请上传相关附件!');
	}
	formInlineRef.value.validate((valid, fields) => {
		if (valid) {
			ElMessageBox.confirm("是否确认发起审批?", "提示", {
				confirmButtonText: "确认发送",
				cancelButtonText: "取消",
				type: "warning",
				confirmButtonClass: "ExitConfirmButton",
				cancelButtonClass: "ExitCancelButton",
			}).then(() => {
				// state.payList = formtabelRef.value.handelData();
				state.tenderTaskId = tenderTaskId;
				BtnLoading.value = true;
				approveApi.saveApplyContract(state).then((res) => {
					if (res.code == 200) {
						ElMessage.success("操作成功");
						pageType.value = "view";
						getApplyContractInfo();
					}
					BtnLoading.value = false;
				});
			});
		}
	});
};
const toPath = () => {
	window.open(state.oaLink);
};

// 获取合同归属部门选项
let departmentArr = ref([]);
let getAllDepartments = async() => {
  let { data } = await department.getAllDepartments();
  departmentArr.value = data
}

onMounted(() => {
  getApplyContractInfo();
  getAllDepartments();
});
</script>
<style lang="scss" scoped>
.tenderContractDetails {
	.contenForm {
		width: 100%;
		border-radius: 10px;
		border: 1px solid #e3e7f1;
		padding: 32px 72px 32px 0;
		.el-form-item,
		.el-select {
			width: 100%;
		}
		.el-col {
			margin-bottom: 15px;
		}
	}
	.card_box {
		border-radius: 10px;
		border: 1px solid #e3e7f1;
		padding: 40px 35px;
		.title {
			span {
				color: #f12527;
			}
			height: 16px;
			font-size: 16px;
			font-weight: bold;
			color: #1a1a1a;
			line-height: 40px;
		}
		.selecAll {
			line-height: 40px;
		}
		.el-button {
			border: 1px solid #fc7018;
			border-radius: 20px;
			color: #fc7018;
			width: 114px;
			height: 40px;
		}

		.card_content {
			padding: 0 69px;
			.file-content-item {
				.button-download {
					width: 77px;
					height: 32px;
					background: linear-gradient(180deg, #ffd091 0%, #ffa557 100%);
					border-radius: 4px;
					cursor: pointer;

					.icon {
						width: 18px;
						height: 18px;
					}
					span {
						color: #ffffff;
					}
				}
				.delete-icon {
					width: 20px;
					height: 20px;
					cursor: pointer;
				}
			}
		}
	}
	.other {
		border-radius: 10px;
		border: 1px solid #e3e7f1;
		padding: 32px 72px;
		justify-content: space-between;
		.other_item {
			.lebel {
				font-size: 16px;
				font-weight: 700;
				color: #1a1a1a;
				line-height: 40px;
			}
			.conetnt {
				width: 300px;
				height: 40px;
				background: #f7f7fa;
				border-radius: 4px;
				line-height: 40px;
				padding-left: 20px;
			}
		}
	}
	.title_ {
		font-size: 16px;
		font-weight: bold;
		color: #1a1a1a;
		line-height: 24px;
	}
	:deep(.el-date-editor) {
		height: 40px;
	}
	:deep(.el-input__wrapper) {
		width: 100%;
	}
	:deep(.el-input) {
		width: 100%;
	}
}
.submitBth {
	position: fixed;
	top: 80%;
	right: 120px;
	z-index: 999;
	.el-button {
		box-shadow: 0px 0px 12px 0 rgba(0, 0, 0, 0.12);
	}
}
:deep(.el-form-item__label, .fz_ ) {
	font-size: 12px !important;
}
</style>
<style lang="scss" scoped>
:deep(.form_table ){
	margin-bottom: 40px;
	margin-left: 180px;
}
</style>
